<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;

/**
 * 分销商处理相关接口
 */
class Distributor extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试方法
     */
    public function test()
    {
        //模拟登录
        $this->auth->direct(2);
        $res = $this->auth->getUserinfo();
        $this->success('返回成功', $res);
    }

    /**
     * 申请成为分销商(已提交过申请则为修改)
     * @param string $name 姓名
     * @param int $mobile 手机号
     * @param int $captcha 手机验证码 验证码发送接口在sms中的send
     * @param int $remark 备注
     */
    public function applyTobeDistributor()
    {
        $user_id = $this->auth->id;

        $name = $this->request->post('name', '用户'.rand(100000,999999));
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        $remark = $this->request->post('remark', '');
        if(!preg_match('/^1[3-9]\d{9}$/', $mobile)) $this->error('联系人手机号格式有误');

        $ret = Sms::check($mobile, $captcha, 'distributorapply');//验证码发送事件 如register=注册，changemobile=修改手机号，playmateapply=申请成为分销商
        if (!$ret) $this->error(__('验证码不正确'));

        $where = [];
        $where['user_id'] = $user_id;
        $agentInfo = db('agent')->where($where)->find();
        $nowTime = time();
        if(!empty($agentInfo)){
            if(in_array($agentInfo['status'], [0,1])) $this->error('已存在您的分销商申请信息，无需再次发起申请');
            //申请过 未通过 则修改
            $data = [
                'name' => $name,
                'mobile' => $mobile,
                'status' => 0,
                'remark' => $remark,
                'updatetime' => $nowTime
            ];
            $res = db('agent')->where('user_id', $user_id)->update($data);
        }else{
            //创建一条分销商申请单
            $data = [
                'user_id' => $user_id,
                'name' => $name,
                'mobile' => $mobile,
                'status' => 0,
                'remark' => $remark,
                'createtime' => $nowTime
            ];
            $res = db('agent')->insert($data);
        }

        if($res) $this->success('已提交申请，请等待审核');
        else $this->error('申请提交失败，请重新操作');
    }

    /**
     * 获取当前"分销商申请"状态
     */
    public function getDistributorStatus()
    {
        $user_id = $this->auth->id;
        $where = [];
        $where['user_id'] = $user_id;
        $agentInfo = db('agent')->where($where)->field('user_id,status')->find();
        $this->success('ok', $agentInfo);
    }

}
